import hashlib
from models.models.RequestResult import RequestResult as Res
from django.views.decorators.csrf import csrf_exempt
from django.http.response import JsonResponse
from models.models import StoreUser
from django.shortcuts import render
import json
import math


# 转发到客户管理页
def to_user(request):
    fields = StoreUser.get_fields()
    res = {
        "name": "商城用户",
        "fields": fields,
        "selectValues": "",
        "getListUrl": "/admin/storeUser/getList/",
        "deleteUrl": "/admin/storeUser/delete/"
    }
    return render(request, "storeAdmin/common/list.html", res)


# 获取用户列表
def get_user_list(request):
    page_number = request.GET.get("page_number")
    if page_number is None:
        page_number = 1
    else:
        page_number = int(page_number)
    page_size = 10
    limit = (page_number - 1) * page_size
    offset = limit+page_size
    count = 0
    users = []
    user_email = request.GET.get("user_email")
    if not user_email:
        users = StoreUser.objects.filter().order_by("-id")[limit:offset]
        count = StoreUser.objects.filter().count()
    else:
        users = StoreUser.objects.filter(user_email__contains=user_email).order_by("-id")[limit:offset]
        count = StoreUser.objects.filter(user_email__contains=user_email).count()
    page_total = math.ceil(count / page_size)
    res_users = []
    for user in users:
        res_user = dict()
        res_user["id"] = user.id
        res_user["user_email"] = user.user_email
        res_user["user_pass"] = user.user_pass
        res_user["nick_name"] = user.nick_name
        res_user["user_icon"] = user.user_icon
        res_users.append(res_user)
    res_date = dict()
    res_date["list"] = res_users
    res_date["page_number"] = page_number
    res_date["page_total"] = page_total
    return JsonResponse(Res.success(res_date))


# 获取某一管理员用户
def get_user_one(request):
    id = request.GET.get('id')
    user = StoreUser.objects.filter(id=id).first()
    return JsonResponse(user.to_dict())


# 删除用户
def delete(request):
    id = request.GET.get("id")
    user = StoreUser.objects.filter(id=id).first()
    user.delete()
    return JsonResponse(Res.success(None))
